<template>
  <VPage edit>
    <el-tabs class="border-card" v-model="activeName">
      <el-tab-pane label="基本详情" name="1">
        <el-form label-width="200px" ref="formRef" :model="formData.orderSource" scroll-to-error class="formw200">
          <div class="formBox">
            <FormTitle title="基本信息" />

            <el-form-item label="渠道店铺名称:">
              <el-input class="input" v-model="formData.orderSource.shop" disabled placeholder="渠道店铺名称" />
            </el-form-item>
            <el-form-item label="真实店铺名称:" prop="name">
              <el-input class="input" v-model="formData.orderSource.real_shop_name" disabled placeholder="真实店铺名称" />
            </el-form-item>
            <el-form-item label="所属平台:" prop="city">
              <el-input class="input" v-model="formData.orderSource.platform" disabled placeholder="所属平台" />
            </el-form-item>
            <el-form-item label="站点国家:" disabled>
              <el-input class="input" v-model="formData.orderSource.site" disabled placeholder="站点国家" />
            </el-form-item>
            <el-form-item label="发货时效（天）:">
              <el-input class="input" type="number" v-model="formData.orderSource.shipping_time" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="提前提醒（小时）:">
              <el-input class="input" type="number" v-model="formData.orderSource.early_reminder" placeholder="请输入" />
            </el-form-item>

            <FormTitle title="税率设置" />
            <el-form-item label="VAT税号:">
              <el-input class="input" v-model="formData.orderSource.vat_tax_code" placeholder="VAT税号" />
            </el-form-item>
            <el-form-item label="VAT税率:">
              <el-input class="input" type="number" v-model="formData.orderSource.vat_tax_rate" placeholder="VAT税率" /><span class="ml-2">%用于导出订单发票等显示</span>
            </el-form-item>
            <el-form-item label="寄件人税号（IOSS）:">
              <el-input class="input" v-model="formData.orderSource.sander_tax_id" placeholder="寄件人税号（IOSS）" />
            </el-form-item>
            <el-form-item label="EORI税号:">
              <el-input class="input" v-model="formData.orderSource.eori_tax_code" placeholder="EORI税号" />
            </el-form-item>
            <el-form-item label="运营成本:">
              <el-input class="input" v-model="formData.orderSource.operating_costs" oninput="value=value.replace(/^(\d{1,3}(\.\d{0,2})?).*/, '$1');" placeholder="运营成本" /><span class="ml-2"
                >%只保留两位小数，计算订单利润时用到</span
              >
            </el-form-item>
            <el-form-item label="汇率折损:">
              <el-input class="input" v-model="formData.orderSource.loss_exchange_ratio" oninput="value=value.replace(/^(\d{1,3}(\.\d{0,2})?).*/, '$1');" placeholder="汇率折损" /><span class="ml-2"
                >%只保留两位小数，计算订单利润时用到</span
              >
            </el-form-item>

            <FormTitle title="渠道人员设置" />

            <el-form-item label="店铺负责人:">
              <select-personnel style="width: 300px" v-model="formData.orderSource.shop_manager_id" placeholder="店铺负责人" @change="changeShopManage" disabled></select-personnel>
            </el-form-item>
            <el-form-item label="店铺店员:">
              <div>
                <select-personnel style="width: 300px" v-model="formData.orderSource.shop_clerks_id" placeholder="店铺店员" :multiple="true" @change="changeShopClerk" disabled></select-personnel>
              </div>
            </el-form-item>
            <el-form-item label="客服人员:">
              <select-personnel style="width: 300px" v-model="formData.orderSource.customer_service_id" placeholder="客服人员" @change="changeShopCustomer" disabled></select-personnel>
            </el-form-item>

            <FormTitle title="渠道设置" />

            <el-form-item label="合并相同地址订单包裹:">
              <el-checkbox v-model="formData.orderSource.is_marge_orders_address" :true-value="1" :false-value="0" label="勾选后，渠道下订单会进入可合并池进行合并包裹的后续操作" />
            </el-form-item>
            <el-form-item label="是否打印包裹感谢信:">
              <el-checkbox v-model="formData.orderSource.is_thank_notes" :true-value="1" :false-value="0" label="勾选后，打印页面时，会同时打印出来。" />
              <el-select v-model="formData.orderSource.thank_letter_id" placeholder="Select">
                <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value" placeholder="请选择" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单优先级别:">
              <el-select v-model="formData.orderSource.order_priority_level" placeholder="请选择">
                <el-option v-for="item in order_priority_level" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <div>说明：设置店铺的订单优先级别，订单优先级越高，越优先配货。</div>
            </el-form-item>
            <el-form-item label="订单发票模板:">
              <el-select v-model="formData.orderSource.invoice_template_id" placeholder="请选择">
                <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="回邮物流商:" prop="return_carrier" :rules="[{ required: true, message: '请选择回邮物流商', trigger: 'change' }]" v-if="formData.orderSource.platform == 'otto'">
              <el-select v-model="formData.orderSource.return_carrier" placeholder="请选择" clearable>
                <el-option :value="1" label="DHL" />
                <el-option :value="2" label="GLS" />
                <el-option :value="3" label="HERMES" />
              </el-select>
            </el-form-item>

            <el-divider> 温馨提示：以下所有服务，需结合自身情况确认开不开启该服务！ </el-divider>

            <el-form-item label="是否下载订单:">
              <el-checkbox v-model="formData.orderSource.is_download_orders" :true-value="1" :false-value="0" label="开启" disabled />
            </el-form-item>
            <el-form-item label="是否预生成追踪号:">
              <el-checkbox v-model="formData.orderSource.is_pre_generate" label="开启" :true-value="1" :false-value="0" disabled />
            </el-form-item>
            <el-form-item label="是否标记平台发货:">
              <div>
                <el-checkbox v-model="formData.orderSource.is_platform_shipment" label="开启" :true-value="1" :false-value="0" disabled />
                <p class="warn">说明：请认真填写和勾选配置信息，例如：[是否预生成追踪号][是否标记平台发货]等这些关乎账号安全的,必须根据自己的需求进行选择设置，务必认真，务必准确！！！</p>
              </div>
            </el-form-item>
            <el-form-item label="状态:">
              <el-switch v-model="formData.orderSource.status" :active-value="1" :inactive-value="0" inline-prompt active-text="启用" inactive-text="禁用" disabled />
            </el-form-item>
          </div>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="店铺发货地址设置" name="2">
        <div class="formBox h-[100%]" v-if="activeName == 2">
          <div style="margin-bottom: 5px"><el-button type="primary" @click="addAdress">添加</el-button></div>
          <el-table :data="formData.shopAddress" border style="width: 100%; height: calc(100vh - 260px)">
            <el-table-column fixed prop="name" label="姓名" width="100" />
            <el-table-column prop="preferred_address" label="街道地址" width="350">
              <template #default="scope">
                <div>
                  {{ scope.row.preferred_address ? scope.row.preferred_address : "" }}
                </div>
                <div>
                  {{ scope.row.alternate_address ? scope.row.alternate_address : "" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="city" label="城市" />
            <el-table-column prop="district" label="区/县" />
            <el-table-column prop="zip_code" label="邮政编码" />
            <el-table-column prop="shipping_name" label="运输类型"></el-table-column>
            <el-table-column prop="is_default_address" label="默认地址">
              <template #default="scope">
                <div>
                  {{ scope.row.is_default_address ? "是" : "否" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="{ row, $index }">
                <el-button link type="primary" size="small" @click="EditAdress(row, $index)">编辑</el-button>
                <el-button link type="danger" size="small" @click="deleteAdress($index, row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="发票地址设置" name="3">
        <div class="form-address">
          <el-form label-width="200px" :model="formData.invoiceAddress" :rules="rules" ref="ruleFormRef" class="formw200">
            <el-form-item label="店铺名称:">
              <SelectShop class="shopName" v-model="formData.invoiceAddress.source_shop_id" @change="changeShop"> </SelectShop>
              <el-button type="primary" @click="syncAddress">同步发票地址</el-button>
            </el-form-item>
            <el-form-item label="姓名:" prop="name">
              <el-input v-model="formData.invoiceAddress.name" placeholder="姓名" />
            </el-form-item>
            <el-form-item label="街道地址1:" prop="preferred_address">
              <el-input v-model="formData.invoiceAddress.preferred_address" placeholder="街道地址1" />
            </el-form-item>
            <el-form-item label="街道地址2:">
              <el-input v-model="formData.invoiceAddress.alternate_address" placeholder="街道地址2" />
            </el-form-item>
            <el-form-item label="城市:" prop="city">
              <el-input v-model="formData.invoiceAddress.city" placeholder="城市" />
            </el-form-item>
            <el-form-item label="区/县:">
              <el-input v-model="formData.invoiceAddress.district" placeholder="区/县" />
            </el-form-item>
            <el-form-item label="州/省:">
              <el-input v-model="formData.invoiceAddress.province" placeholder="州/省" />
            </el-form-item>
            <el-form-item label="国家:" prop="country_id">
              <SelectCountry class="w-full" v-model="formData.invoiceAddress.country_id" valueKey="id" placeholder="请选择国家"> </SelectCountry>
            </el-form-item>
            <el-form-item label="邮政编码:">
              <el-input v-model="formData.invoiceAddress.zip_code" type="number" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="公司名称:">
              <el-input v-model="formData.invoiceAddress.company_name" placeholder="公司名称" />
            </el-form-item>
            <el-form-item label="电话:" prop="telephone">
              <el-input v-model="formData.invoiceAddress.telephone" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="手机号码:" prop="mobile_number">
              <el-input v-model="formData.invoiceAddress.mobile_number" placeholder="手机号码" />
            </el-form-item>
            <el-form-item label="传真:">
              <el-input v-model="formData.invoiceAddress.fax" placeholder="传真" />
            </el-form-item>
            <el-form-item label="邮箱:" prop="email">
              <el-input v-model="formData.invoiceAddress.email" placeholder="邮箱" />
            </el-form-item>
            <el-form-item label="网址:">
              <el-input v-model="formData.invoiceAddress.web_site" placeholder="网址" />
            </el-form-item>
            <el-form-item label="银行信息:">
              <el-input v-model="formData.invoiceAddress.bank_info" placeholder="银行信息" />
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div style="text-align: center" class="footer-btn">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="save" v-if="activeName != 2">保存</el-button>
    </div>
    <VshippingAddress ref="shippingAddress" class="dialogPublic" @add="addAddressConfirm" @edit="editAddressConfirm" @query="detailF" />
  </VPage>
</template>

<script setup name="Basic-setupOrder-sourceEdit" lang="jsx">
import { onMounted, reactive, toRefs } from "vue"
import { useRouter } from "vue-router"
import { overallOptions } from "@/api/public"
import { orderSourceCreate, orderSourceDetail, getShopShippingAddress, orderSourcedeleteAdress } from "../api"
import VshippingAddress from "../components/shippingAddress"
import { ElMessage } from "element-plus"
import SelectShop from "@/components/Selects/SelectShop"
import SelectCountry from "@/components/Selects/SelectCountry"
import action from "@/utils/action.js"
import FormTitle from "@/components/XForm/FormTitle.vue"
const router = useRouter()
const data = reactive({
  formData: {
    orderSource: {},
    shopAddress: [],
    invoiceAddress: {},
  },
  order_priority_level: [],
  invoiceAddress: [],
  tag_type: 0,
  messageSetData: {},
  editAddressIndex: 0,
})
const { formData, invoiceAddress, order_priority_level, editAddressIndex } = toRefs(data)
const activeName = ref("1")
const changeShopManage = (list) => {
  if (list.length) {
    formData.value.orderSource.shop_manager = list[0].text
  } else {
    formData.value.orderSource.shop_manager = ""
  }
}

const changeShopClerk = (list) => {
  if (list.length) {
    const shop_clerks = []
    list.forEach((i) => {
      if (i.value) {
        shop_clerks.push({
          name: i.text,
          id: i.value,
        })
      }
    })
    formData.value.orderSource.shop_clerks = shop_clerks.map((v) => v.name)
  } else {
    formData.value.orderSource.shop_clerks = []
  }
}

const changeShopCustomer = (list) => {
  if (list.length) {
    formData.value.orderSource.customer_service = list[0].text
  } else {
    formData.value.orderSource.customer_service = ""
  }
}

//座机验证
const checktelephone = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const reg = /^0\d{2,3}[-]?\d{7,8}|0\d{2,3}\s?\d{7,8}$/
    if (reg.test(value)) {
      callback()
    } else {
      return callback(new Error("请输入正确的电话"))
    }
  }
}
//手机号验证
const checkPhone = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    //验证手机号
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
    //验证区号
    const phoneReg = /^\d{3}-\d{8}|\d{4}-\d{7}$/
    if (reg.test(value) || phoneReg.test(value)) {
      callback()
    } else {
      return callback(new Error("请输入正确的联系电话"))
    }
  }
}
const checkEmail = (rule, value, callback) => {
  const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
  if (!value) {
    callback()
  }
  setTimeout(() => {
    if (mailReg.test(value)) {
      callback()
    } else {
      callback(new Error("请输入正确的邮箱格式"))
    }
  }, 100)
}
const rules = reactive({
  country_id: [{ required: true, message: "请选择", trigger: "change" }],
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  preferred_address: [{ required: true, message: "不能为空", trigger: "blur" }],
  city: [{ required: true, message: "不能为空", trigger: "blur" }],
  mobile_number: [{ validator: checkPhone, trigger: "blur" }],
  email: [{ validator: checkEmail, trigger: "blur" }],
  telephone: [{ validator: checktelephone, trigger: "blur" }],
})

onMounted(() => {
  overallOptions({ params: ["base.orderSourceChannel"] }).then((res) => {
    order_priority_level.value = res.data.baseOrderSourceChannel.order_priority_level
  })
  detailF()
})

onActivated(() => {
  nextTick(() => {}).then(() => {
    detailF()
  })
})

const detailF = () => {
  const id = router.currentRoute.value.query.id
  if (id) {
    orderSourceDetail({ id }).then((res) => {
      if (res.data.orderSource.shop_clerks_id) {
        res.data.orderSource.shop_clerks_id = res.data.orderSource.shop_clerks_id.map(Number)
      }
      res.data.invoiceAddress = res.data.invoiceAddress || {
        country_id: "",
      }
      formData.value = res.data
      invoiceAddress.value = res.data.invoiceAddress
    })
  }
}

const formRef = ref()
const ruleFormRef = ref()

//保存
const save = () => {
  let params = { ...formData.value }
  if (activeName.value == 1) {
    console.log(params)
    params = {
      id: params.id,
      orderSource: params.orderSource,
      shopAddress: [],
      invoiceAddress: {},
    }
    formRef.value.validate((valid) => {
      console.log(valid)

      if (valid) {
        try {
          console.log(params)
          orderSourceCreate(params)
          ElMessage({ message: "保存成功！", type: "success" })
          handleCancel()
        } catch (error) {}
      } else {
        console.log("error submit!")
        return false
      }
    })
  }
  console.log(activeName.value)

  if (activeName.value == 3) {
    params = {
      id: params.id,
      orderSource: {},
      shopAddress: [],
      invoiceAddress: params.invoiceAddress,
    }
    ruleFormRef.value.validate((valid) => {
      if (valid) {
        try {
          orderSourceCreate(params)
          ElMessage({ message: "保存成功！", type: "success" })
          handleCancel()
        } catch (error) {}
      } else {
        console.log("error submit!")
        return false
      }
    })
  }
}

const handleCancel = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "closeActiveTab",
    },
  })
}

const changeShop = (val) => {
  formData.value.invoiceAddress.source_shop = val
}

const syncAddress = async () => {
  if (!formData.value.invoiceAddress.source_shop_id) {
    ElMessage.error("请选择店铺")
    return
  }
  try {
    const res = await getShopShippingAddress({
      shop_id: formData.value.invoiceAddress.source_shop_id,
      address_type: 1,
    })
    if (!res.data.length) {
      ElMessage.error("店铺发票地址为空，请检查再进行同步操作")
      return
    }
    formData.value.invoiceAddress = {
      ...res.data?.[0],
      source_shop_id: formData.value.invoiceAddress.source_shop_id,
      source_shop: formData.value.invoiceAddress.source_shop,
    }
  } catch (e) {
    throw Error(e)
  }
}

const shippingAddress = ref()

// 添加地址
const addAdress = () => {
  const arr = [formData.value.id]
  shippingAddress?.value.open("add", arr)
}
// 发货地址编辑
const EditAdress = (row, index) => {
  const arr = [formData.value.id]
  editAddressIndex.value = index
  shippingAddress?.value.open("edit", arr, Object.assign({}, row))
}
// 发货地址删除
const deleteAdress = async (index, row) => {
  if (row.id) {
    await orderSourcedeleteAdress({ id: row.id })
  } else {
    formData.value.shopAddress.splice(index, 1)
  }
  detailF()
}
const addAddressConfirm = async (row, callback) => {
  let params = JSON.parse(JSON.stringify(formData.value))
  params.shopAddress.push(row)
  // console.log(params)
  params = {
    ...params,
    orderSource: {},
    invoiceAddress: {},
  }
  await orderSourceCreate(params)
  callback()
}

const editAddressConfirm = async (row, callback) => {
  let params = JSON.parse(JSON.stringify(formData.value))
  params.shopAddress.splice(editAddressIndex.value, 1, row)

  params = {
    ...params,
    orderSource: {},
    invoiceAddress: {},
  }
  await orderSourceCreate(params)
  callback()
}
</script>

<style lang="scss" scoped>
.el-tabs--border-card {
  border: none;
}
.border-card {
  // background: #fff;
  background-color: var(--base-color);
  padding: 0 16px 16px;
}
.card-header {
  :deep(.form-title) {
    margin-bottom: 0;
  }
}
.formTitle {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 10px;
}

.formw200 {
  :deep(.input) {
    width: 300px;
  }
}

.form-address {
  width: 800px;
  height: calc(100vh - 260px);
}

.warn {
  line-height: 20px;
  color: #f00;
}

:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}

:deep(.el-input__inner) {
  line-height: 1px !important;
}

.el-form {
  margin-right: 60px;

  :deep(.shopName) {
    width: calc(100% - 127px);
    margin-right: 10px;
  }
}
:deep(.el-tabs__content) {
  margin-bottom: 30px;
}
.footer-btn {
  position: fixed;
  width: calc(100% - 88px);
  padding: 8px 0;
  // background: #fff;
  background-color: var(--base-color);
  bottom: 0;
  // border-top: 1px solid #e4e7ed;
  border-top: 1px solid var(--base-border-color);
  z-index: 999;
}
</style>
